package com.gold.common;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.InvalidClaimException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import java.util.*;

/**
 * @author XiaoHao
 * @date 2022-05-07 16:22
 */
@Slf4j
public class TokenUtil {
    //过期时间设置(30分钟)
//    private static final long EXPIRE_TIME = 30*60*1000;
    private static final long EXPIRE_TIME = 60 * 60 * 1000;
    //私钥设置
    public static final String SECRET_KEY = "9527";

    /**
     * 生成token
     *
     * @param name
     * @return
     */
    public static String getToken(String name,String role) {

        //过期时间和加密算法设置
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        Algorithm algorithm = Algorithm.HMAC256(SECRET_KEY);

        //头部信息
        Map<String, Object> header = new HashMap<>(2);
        header.put("typ", "JWT");
        header.put("alg", "HS256");
        return JWT.create()
                .withHeader(header)
                .withClaim("name", name)
                .withClaim("role", role)
//                .withExpiresAt(date)
                .sign(algorithm);

    }

    /**
     * 获取token中的用户
     *
     * @param token
     * @return
     */
    public static String getTokenName(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("name").asString();
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 获取token中的角色
     * @param token
     * @return
     */
    public static List<GrantedAuthority> getTokenRole(String token) {
        try {
            List<GrantedAuthority> list = new ArrayList<>();
            DecodedJWT jwt = JWT.decode(token);
            String role = jwt.getClaim("role").asString();
            String[] split = role.split(",");
            for (String s : split) {
                list.add(new SimpleGrantedAuthority(s));
            }
            return list;
        } catch (Exception e) {
            return null;
        }
    }

    public static String verify(String token) {
        DecodedJWT verify = null;
        try {
            verify = JWT.require(Algorithm.HMAC256(SECRET_KEY)).build().verify(token);
        } catch (SignatureVerificationException e) {
            log.info("签名不一致:" + e.getMessage());
            return "签名不一致";

        } catch (TokenExpiredException e) {
            log.info("令牌过期" + e.getMessage());
            return "令牌过期";

        } catch (AlgorithmMismatchException e) {
            log.info("签名算法不匹配" + e.getMessage());
            return "签名算法不匹配";

        } catch (InvalidClaimException e) {
            log.info("payload不可用" + e.getMessage());
            return "payload不可用";

        } catch (Exception e) {
            log.info("校验失败" + e.getMessage());
            return "校验失败";
        }
        return "";
    }

}
